package cn.stacey.jd.service;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.stacey.jd.dao.ProductIndexDao;
import cn.stacey.jd.domain.Product;

@Service
public class ProductService {
	private static final String REGEX = "\\[(\\*|\\d+) TO (\\d+|\\*)\\]";
	@Autowired
	ProductIndexDao dao;
	public Page<Product> search(
			String keyword,String category,String price,
			Pageable pageable   //pagable里面封装了分页和排序的参数(sort)
			){
		
		BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

		//根据关键字搜索
		if(!StringUtils.isEmpty(keyword)) {
			//用户输入条件比较长的情况
			//先分词在搜索
			QueryStringQueryBuilder builder1 = QueryBuilders.queryStringQuery(keyword)
			.field("name",2)
//			.field("description")
//			.analyzer("ik_smart")    //指定分词器
			.defaultOperator(Operator.OR);  //拆分后的关键字是出现某一个就可以OR
			
			//当用户输入的关键字比较短的情况，还得加一个wildcard query
			WildcardQueryBuilder builder2 = QueryBuilders.wildcardQuery("name", "*"+keyword+"*");
			WildcardQueryBuilder builder3 = QueryBuilders.wildcardQuery("description", keyword);
			
			BoolQueryBuilder keywordQueryBuilder = QueryBuilders.boolQuery()
			.should(builder1)
			.should(builder2)
			.should(builder3);
			
			queryBuilder.must(keywordQueryBuilder);
//			return dao.search(keywordQueryBuilder, pageable);
		}
		
		//根据分类搜索
		if(!StringUtils.isEmpty(category)) {
			TermQueryBuilder categoryQueryBuilder = QueryBuilders.termQuery("category", category);
			queryBuilder.must(categoryQueryBuilder);
			
		}
		
		//根据价格区间搜索[* TO 9]  [10 TO 19] [50 TO *]
		if(!StringUtils.isEmpty(price)) {
		if(price.matches(REGEX)) {
			QueryStringQueryBuilder priceQueryBuilder = 
					QueryBuilders.queryStringQuery("price:"+price);//"price"表示在价格域上面搜索??
			//QueryBuilders.queryStringQuery("price:[0 TO 10]")
			queryBuilder.must(priceQueryBuilder);
		}else {
			throw new RuntimeException("价格不符合范围格式");
		}
		}
		return dao.search(queryBuilder, pageable);
		
	} 
}
